package com.pocketmenu.business;

import java.text.DecimalFormat;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.pocketmenu.persistence.SQLiteHelper;
import com.pocketmenu.ui.R;


public class OrderItemCursorAdapter extends SimpleCursorAdapter {
		
	private int layout;
	private OnTouchListener listener;
	
	public OrderItemCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to, OnTouchListener listener) {
		super(context, layout, c, from, to);		
		this.layout = layout;
		this.listener = listener;
	}
	
	@Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {

        Cursor c = getCursor();

        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(layout, parent, false);
        v.setOnTouchListener(listener);      
        
        return bindValues(v, context, c);
    }

	private View bindValues(View v, Context context, Cursor c)
	{
		int quantityIndex = c.getColumnIndex(SQLiteHelper.COLUMN_ORDER_ITEM_QUANTITY);
    	int nameIndex = c.getColumnIndex(SQLiteHelper.COLUMN_ITEM_NAME);
    	int priceIndex = c.getColumnIndex(SQLiteHelper.COLUMN_ITEM_PRICE);
    	
        int quantity = c.getInt(quantityIndex);
        String name = c.getString(nameIndex);
        int price = c.getInt(priceIndex);                
        
        TextView tvItemQuantityTemp = (TextView) v.findViewById(R.id.tvItemQuantity);
        if (tvItemQuantityTemp != null) {
        	tvItemQuantityTemp.setText(String.valueOf(quantity));
        }

        TextView tvItemNameTemp = (TextView) v.findViewById(R.id.tvItemName);
        if (tvItemNameTemp != null) {
        	tvItemNameTemp.setText(name);
        }
        
        TextView tvItemTotalPriceTemp = (TextView) v.findViewById(R.id.tvItemTotalPrice);
        if (tvItemTotalPriceTemp != null) {            
        	DecimalFormat df = new DecimalFormat("#,###,###");        	
        	tvItemTotalPriceTemp.setText("$" + df.format(price * quantity));
        }
        return v;
	}
	
    @Override
    public void bindView(View v, Context context, Cursor c) {
    	
    	bindValues(v, context, c);
    }    
}
